package it.kion.util.ui.ulog2.views;

import java.text.Collator;
import java.util.Locale;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.viewers.ColumnLayoutData;
import org.eclipse.jface.viewers.ColumnPixelData;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableLayout;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.ViewPart;

public class TableViewPart extends ViewPart {
	protected static final String TAG_COLUMN = "column";
	protected static final String TAG_NUMBER = "number";
	protected static final String TAG_COL_ORDER = "colOrder";
	protected static final String TAG_WIDTH = "width";

	protected static String[] columnHeadersDefault;
	
	protected String columnHeaders[];
	protected ColumnLayoutData columnLayouts[];
	private IAction doubleClickAction;
	private IMemento memento;

	private Table table;
	private TableViewer viewer;
	
	private int[] order;
	
	public void createPartControl(Composite parent) {
		viewer = new TableViewer(parent, SWT.SINGLE | SWT.FULL_SELECTION
				| SWT.H_SCROLL | SWT.V_SCROLL | SWT.CHECK);

		table = viewer.getTable();
		table.setHeaderVisible(true);
		table.setLinesVisible(true);

		createColumns();
		createActions();
		hookMenus();
		hookEvents();
		contributeToActionBars();
	}

	protected void createColumns() {
		if (memento != null) {
			restoreColumnWidths(memento);
		}

		TableLayout layout = new TableLayout();
		table.setLayout(layout);

		Listener listener = new Listener() {
			public void handleEvent(Event e) {
//				TableColumn tc = (TableColumn) e.widget;
//				System.out.println("Muovo " + tc);
			}
		};
		if(columnHeaders==null) {
			columnHeaders = columnHeadersDefault;
		}
		
		for (int i = 0; i < columnHeaders.length; i++) {
			TableColumn tc = new TableColumn(table, SWT.NONE, i);
			tc.setText(columnHeaders[i]);
			tc.setResizable(columnLayouts[i].resizable);
			tc.setMoveable(true);
			tc.addListener(SWT.Move, listener);
			layout.addColumnData(columnLayouts[i]);
			Listener sortListener = new TCListener(tc);
			tc.addListener(SWT.Selection, sortListener);
		}

		table.setSortDirection(SWT.UP);
		restoreColumnOrder();
	}

	private void restoreColumnOrder() {
		if(order!=null && order.length==6) {
			table.setColumnOrder(order);	
		}
	}

	private class TCListener implements Listener {

		private TableColumn column;
		
		private int sd = SWT.UP;

		public TCListener(TableColumn tc) {
			this.column = tc;
		}

		public void handleEvent(Event e) {
			int indx = column.getParent().indexOf(column);
			TableItem[] items = column.getParent().getItems();
			for (int i = 1; i < items.length; i++) {
				String value1 = items[i].getText(indx);
				for (int j = 0; j < i; j++) {
					String value2 = items[j].getText(indx);
					if (compare(value1, value2)) {
						final int cconut = column.getParent().getColumnCount();
						String[] values = new String[cconut];					
						for(int col = 0; col<cconut; col++) {
							values[col] = items[i].getText(col);
						}
						Color fg = items[i].getForeground();
						Color bg = items[i].getBackground();
						items[i].dispose();
						TableItem item = new TableItem(table, SWT.NONE, j);
						item.setText(values);
						item.setBackground(bg);
						item.setForeground(fg);
						items = table.getItems();
						break;
					}
				}
			}
			table.setSortDirection(sd);
			table.setSortColumn(column);
			sd = (sd == SWT.UP) ? SWT.DOWN : SWT.UP;
		}
		
		private boolean compare(String v1, String v2){
			final Collator collator = Collator.getInstance(Locale.getDefault());
			return (sd == SWT.UP) ? (collator.compare(v1, v2) < 0) : (collator.compare(v1, v2) > 0);
		}
		
	}
	
	

	protected void restoreColumnWidths(IMemento memento) {
		IMemento children[] = memento.getChildren(TAG_COLUMN);
		order = new int[6];
		if (children != null) {
			for (int i = 0; i < children.length; i++) {
				Integer val = children[i].getInteger(TAG_NUMBER);
				if (val != null) {
					int index = val.intValue();
					val = children[i].getInteger(TAG_WIDTH);
					if (val != null) {
						columnLayouts[index] = new ColumnPixelData(val.intValue(), true);
					}
				}
				
				// Ordine delle colonne
				val = children[i].getInteger(TAG_COL_ORDER);
				if (val != null && i<order.length) {
					int index = val.intValue();
					order[i] = index; 
				}
				
			}
		}
		
	}

	protected void saveColumnWidths(IMemento memento) {
		Table table = viewer.getTable();
		TableColumn columns[] = table.getColumns();

		for (int i = 0; i < columns.length; i++) {
			IMemento child = memento.createChild(TAG_COLUMN);
			if (columnLayouts[i].resizable) {
				
				child.putInteger(TAG_NUMBER, i);
				child.putInteger(TAG_WIDTH, columns[i].getWidth());
			} 
			child.putInteger(TAG_COL_ORDER, table.getColumnOrder()[i]);	
		}
	}

	protected void hookMenus() {
		MenuManager menuMgr = new MenuManager("#PopupMenu");
		menuMgr.setRemoveAllWhenShown(true);
		menuMgr.addMenuListener(new IMenuListener() {
			public void menuAboutToShow(IMenuManager manager) {
				TableViewPart.this.fillContextMenu(manager);
			}
		});
		Menu menu = menuMgr.createContextMenu(viewer.getControl());
		viewer.getControl().setMenu(menu);
		getSite().registerContextMenu(menuMgr, viewer);
	}

	protected void hookEvents() {
		viewer.addSelectionChangedListener(new ISelectionChangedListener() {
			public void selectionChanged(SelectionChangedEvent event) {
				if (event.getSelection() != null)
					TableViewPart.this.selectionChanged(event);
			}
		});
		viewer.addDoubleClickListener(new IDoubleClickListener() {
			public void doubleClick(DoubleClickEvent event) {
				doubleClickAction.run();
			}
		});
	}

	protected void contributeToActionBars() {
		IActionBars bars = getViewSite().getActionBars();
		fillLocalPullDown(bars.getMenuManager());
		fillLocalToolBar(bars.getToolBarManager());
	}

	public void saveState(IMemento memento) {
		if (viewer == null) {
			if (this.memento != null) // Mantengo il vecchio stato
				memento.putMemento(this.memento);
			return;
		}

		saveColumnWidths(memento);
	}

	public void init(IViewSite site, IMemento memento) throws PartInitException {
		super.init(site, memento);
		this.memento = memento;
	}

	public void setFocus() {
		viewer.getControl().setFocus();
	}

	public Table getTable() {
		return table;
	}

	public TableViewer getViewer() {
		return viewer;
	}

	public void setColumnHeaders(String[] strings) {
		columnHeaders = strings;
	}

	public void setColumnLayouts(ColumnLayoutData[] data) {
		columnLayouts = data;
	}

	public void setDoubleClickAction(IAction action) {
		doubleClickAction = action;
	}

	protected void fillContextMenu(IMenuManager manager) {
	}

	protected void fillLocalPullDown(IMenuManager manager) {
	}

	protected void fillLocalToolBar(IToolBarManager manager) {
	}

	protected void selectionChanged(SelectionChangedEvent event) {
	}

	protected void createActions() {
	}
}